package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.TrajectoryListAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseFragmentActivity;
import com.bjesc_b2c.app.appraiset.mvp.presenter.CusDetailsPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.CusDetailsPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CusDetailsView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.MapUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import master_bean.CustomerDetailsBean;
import rxretrofit_base.model.KeyBean;

/**
 * Created by yidong on 2017/5/24.
 */

public class CustomerDetailsActivity extends BaseFragmentActivity implements View.OnClickListener, CusDetailsView {
    @Bind(R.id.id_flowlayout)
    TagFlowLayout mFlowLayout;
    @Bind(R.id.tv_title)
    TextView title;
    @Bind(R.id.tv_demand_car)
    TextView demandTv;
    @Bind(R.id.tv_tourist_name)
    TextView touristsNameTv;
    @Bind(R.id.tv_status)
    TextView statusTv;
    @Bind(R.id.tv_dealer_address)
    TextView dealerAddressTv;
    @Bind(R.id.tv_dealer_name)
    TextView dealerNameTv;
    @Bind(R.id.tv_dealer_boss)
    TextView dealerBossTv;
    @Bind(R.id.tv_next_follow_time)
    TextView nextTimeTv;
    @Bind(R.id.tv_car_id)
    TextView carIdTv;
    @Bind(R.id.tv_follow_content)
    TextView followContentTv;
    @Bind(R.id.scroll_view)
    ScrollView scrollView;

    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.rvTrace)
    RecyclerView recyclerView;
    private TagAdapter adapter;
    private CusDetailsPresenter presenter;
    private String telNumber = "";
    private String bossTelNumber = "";
    private String dispatch_id;
    private List<String> touifo = new ArrayList<>();
    private TrajectoryListAdapter trajectoryListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_details);
        ButterKnife.bind(this);
        title.setText("订单详情");
        returnLin.setVisibility(View.VISIBLE);
        presenter = new CusDetailsPresenterImpl(this);
        dispatch_id = CustomSharedPreferences.getString(this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        presenter.getDetails(dispatch_id, 1);//订单类型；1，订单 2，意向客源
        adapter = new TagAdapter<String>(touifo) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(mActivity).inflate(R.layout.layout_tou_tag_view, mFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        };
        mFlowLayout.setAdapter(adapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void loadStart() {
        showLoading("加载中...");
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
    }

    @Override
    public void loadFailure() {
        cancelLoading();
    }

    @OnClick({R.id.iv_tourist_phone, R.id.tv_car_info, R.id.iv_return,
            R.id.iv_tourist_message, R.id.iv_boss_phone, R.id.iv_edit,
            R.id.tv_same_price})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_return:    //返回
                finish();
                break;
            case R.id.iv_boss_phone:
                if (!TextUtils.isEmpty(bossTelNumber)) {
                    call(bossTelNumber);
                } else {
                    showToast("没有获取到电话号码");
                }
                break;
            case R.id.iv_tourist_phone: //打电话
                if (!TextUtils.isEmpty(telNumber)) {
                    call(telNumber);
                } else {
                    showToast("没有获取到电话号码");
                }
                break;
            case R.id.iv_tourist_message: //发短信
                if (!TextUtils.isEmpty(telNumber)) {
                    sendto(telNumber);
                } else {
                    showToast("没有获取到电话号码");
                }
                break;
            case R.id.iv_edit: //客户详情
                Intent cIntent = new Intent(mActivity, CustomerInfoActivity.class);
                cIntent.putExtra("TYPE", 1);
                startIntent(cIntent, false);
                break;
            case R.id.tv_same_price://同款同价车
                Intent pIntent = new Intent(mActivity, SamePriceActivity.class);
                pIntent.putExtra("TYPE", 1);
                startActivityForResult(pIntent, 1);
                break;
            case R.id.tv_car_info://
                startIntent(new Intent(mActivity, CarDetailsActivity.class), false);
                break;
            case R.id.btn_return: //订单退回
                Intent rIntent = new Intent(mActivity, TakeLookActivity.class);
                rIntent.putExtra("takeType", 2);
                startActivityForResult(rIntent, 1);
                break;
            case R.id.btn_change_of_contract: //改约
                Intent cdIntent = new Intent(mActivity, TakeLookActivity.class);
                cdIntent.putExtra("takeType", 4);
                startActivityForResult(cdIntent, 1);
                break;
            case R.id.btn_confirm_time: //确认到店时间
                Intent conIntent = new Intent(mActivity, TakeLookActivity.class);
                conIntent.putExtra("takeType", 6);
                startActivityForResult(conIntent, 1);
                break;
            case R.id.btn_move_order://转单
                startIntent(new Intent(mActivity, MoveOrderActivity.class), false);
                break;
        }
    }

    /**
     * 调用拨号功能
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startIntent(intent, false);
    }

    private void sendto(String phone) {
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startIntent(intent, false);
    }

    @Override
    public void getDatas(CustomerDetailsBean data) {
        touifo.addAll(data.getTourists().getDemand());
        Logger.d(data.getTourists().getDemand().size());
        adapter.notifyDataChanged();
        touristsNameTv.setText(data.getTourists().getName());
        statusTv.setText(data.getDispatch_info().getStatus());
        telNumber = data.getTourists().getPhone();
        bossTelNumber = data.getDispatch_info().getDealer_phone();
        demandTv.setText("预约车型：" + data.getDispatch_info().getTitle());
        carIdTv.setText("车源id：" + data.getDispatch_info().getCar_id() + "(盘库时间:" + data.getDispatch_info().getInventory_time() + ")");
        dealerAddressTv.setText("地址：" + data.getDispatch_info().getDealer_address());
        dealerNameTv.setText("经销商：" + data.getDispatch_info().getDealer_name());
        dealerBossTv.setText("经销商联系人：" + data.getDispatch_info().getDealer_boss());
        nextTimeTv.setText("下次跟进时间：" + data.getDispatch_info().getNext_follow_time());
        CustomSharedPreferences.saveString(this, new MapUtil().put(KeyBean.CARID.valueOf(), data.getDispatch_info().getCar_id()).build(), KeyBean.FILE_NAME.valueOf());
        if (data.getFollow_history().size() > 0) {
            followContentTv.setText("最新跟进：" + data.getDispatch_info().getContent() + "(" + data.getFollow_history().get(0).getAdd_time() + ")");
            trajectoryListAdapter = new TrajectoryListAdapter(mActivity, R.layout.layout_item_trajectoy, data.getFollow_history());
            recyclerView.setAdapter(trajectoryListAdapter);
        }
        scrollView.scrollTo(0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 11 || resultCode == 22) {
            presenter.getDetails(dispatch_id, 1);//订单类型；1，订单 2，意向客源
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
